const mongoose = require('mongoose');
const User = require('../models/User');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 数据库连接
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/activity_organizer', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB连接错误:'));
db.once('open', async () => {
  console.log('MongoDB连接成功');
  
  try {
    // 检查是否已存在管理员用户
    const adminUser = await User.findOne({ role: 'admin' });
    
    if (adminUser) {
      console.log('管理员账户已存在:', adminUser.username);
      return mongoose.connection.close();
    }
    
    // 创建管理员用户
    const newAdmin = new User({
      username: 'admin',
      name: '系统管理员',
      email: 'admin@activity-system.com',
      password: 'admin123', // 初始密码，登录后应更改
      role: 'admin',
      status: 'offline'
    });
    
    await newAdmin.save();
    console.log('管理员账户创建成功!');
    console.log('- 用户名: admin');
    console.log('- 密码: admin123');
    console.log('- 邮箱: admin@activity-system.com');
    console.log('请在首次登录后立即更改密码!');
    
  } catch (error) {
    console.error('创建管理员账户失败:', error);
  } finally {
    // 关闭数据库连接
    mongoose.connection.close();
  }
});